package cn.billy.basic.interceptor;

import cn.billy.basic.annotation.PreAuthorize;
import cn.billy.basic.jwt.JwtUtils;
import cn.billy.basic.jwt.Payload;
import cn.billy.basic.jwt.RsaUtils;
import cn.billy.basic.jwt.UserInfo;
import cn.billy.system.mapper.PermissionMapper;
import cn.billy.user.domain.Logininfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;
/*/*
* @Title: LoginInterceptor
* @Description: 登录拦截器
* @Author: Billy
* @Version: 1.0
* @Date:  2022/7/13 16:08
* @Parameters:
* @Return
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String jwtRsaPub;

   /* @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        if (!StringUtils.isEmpty(token)){
            Object logininfo = redisTemplate.opsForValue().get(token);
            if (logininfo != null){
                // 创建了一个新的Logininfo
                Logininfo logininfoTmp = new Logininfo();
                // 使用copy方法实现转换，从object转换为Logininfo类型
                BeanUtils.copyProperties(logininfo,logininfoTmp);
                // 根据传回来的logininfo获取到type判断是否等于0，等于说明他是员工
                if (logininfoTmp.getType() == 0){
                    // 得到本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod)handler;
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (preAuthorize != null) {
                        String sn = preAuthorize.sn();
                        List<String> ownPermissions = permissionMapper.loadOwnPermissionByLogininId(logininfoTmp.getId());
                        if (!ownPermissions.contains(sn)){
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }

                }
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
                return true;
            }

        }

        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;

    }*/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        if (!StringUtils.isEmpty(token)){
            // 1.解析token得到载荷数据
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPub).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            System.out.println("111111"+payload);
            if (payload != null){
                // 1.判断是否是后台用户，如果是进入判断
                UserInfo userInfo = payload.getUserInfo();
                Logininfo logininfo = userInfo.getLogininfo();
                System.out.println("222222"+userInfo.getPermissions());
                // 根据传回来的logininfo获取到type判断是否等于0，等于说明他是员工
                if (logininfo.getType() == 0){
                    // 得到本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod)handler;
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (preAuthorize != null) {
                        String sn = preAuthorize.sn();
                        if (!userInfo.getPermissions().contains(sn)){
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }

                }
                redisTemplate.opsForValue().set(token,logininfo,600, TimeUnit.MINUTES);
                return true;
            }

        }

        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;

    }
}
